import re

from django.contrib.sites.models import Site
from django import http
from django.conf import settings
from accounts.models import *

class AccountMiddleware(object):
    """
    Determines the current Site and Account based on request.get_host().
    Sets `request.site` and `request.account` based on the results (or None if no Site/Account is found).
    """
    
    def _set_site(self, request):
        """
        If settings.SITE_ID is None, tries to find the Site with a domain matching request.get_host().
        Sets `request.site` to the resulting Site, or None if no Site is found.
        """
        site = Site.objects.get(domain__iexact=request.get_host())
        request.site = site
    
    def _set_account(self, request):
        """
        Sets `request.account` to the Account matching the current `request.site`.
        If `request.site` is None, or no Account with the Site exists, `request.account` is set to None.
        """
        if getattr(request, 'site', None) is not None:
            try:
                request.account = Account.objects.get(site=request.site)
            except Account.DoesNotExist:
                request.account = None
        else:
            request.account = None
    
    def process_request(self, request):
        # If going to example.com/parade/, try to redirect them to example.paradepro.com/parade/
        domain = '.'.join(request.get_host().split('.')[-2:]).lower()
        if re.match(r'^/parade/', request.path) and domain != 'paradepro.com' and settings.DEBUG is False:
            # example.com/parade/ was requested.  Find the Account matching 'example.com'
            # and redirect to the same path.
            try:
                account = Account.objects.get(site__domain__iexact=request.get_host())
                return http.HttpResponseRedirect('http://%s.paradepro.com%s' % (account.label, request.path))
            except Account.DoesNotExist:
                return http.HttpResponseNotFound("Site wasn't found.")
        
        try:
            self._set_site(request)
        except Site.DoesNotExist:
            # Maybe they went to a subdomain that's now using a custom domain (and thus no longer resolves).
            # If that's the case, try to use the subdomain to find an Account and redirect to it's domain. 
            try:
                account = Account.objects.get(label__iexact=request.get_host().split('.')[0])
                request.site = account.site
                # Unless the path starts with admin URL, redirect them.
                if not re.match(r'^/parade/', request.path):
                    return http.HttpResponseRedirect('http://%s' % account.site.domain)
            except:
                # TODO: what happens when someone goes to a site that doesn't exist?
                return http.HttpResponseNotFound("Site wasn't found.")
            
        self._set_account(request)

        # Add references 
        from accounts.thread_settings import set_thread_vars
        set_thread_vars(request=request, account=request.account, site=request.site)
        return None
